const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

const inputDir = 'md-docs';
const outputDir = 'docx-output';

function convertMdToDocx(inputPath) {
  const relativePath = path.relative(inputDir, inputPath);
  const outputPath = path.join(outputDir, relativePath.replace(/\.md$/, '.docx'));
  const outputFolder = path.dirname(outputPath);

  if (!fs.existsSync(outputFolder)) {
    fs.mkdirSync(outputFolder, { recursive: true });
  }

  exec(`pandoc "${inputPath}" -o "${outputPath}"`, (error) => {
    if (error) {
      console.error(`❌ Failed to convert ${inputPath}:`, error.message);
    } else {
      console.log(`✅ Converted: ${inputPath} -> ${outputPath}`);
    }
  });
}

function walkDir(dir) {
  fs.readdirSync(dir).forEach(file => {
    const fullPath = path.join(dir, file);
    if (fs.statSync(fullPath).isDirectory()) {
      walkDir(fullPath);
    } else if (file.endsWith('.md')) {
      convertMdToDocx(fullPath);
    }
  });
}

walkDir(inputDir);